//#include "test1.hh"





#include <misc_utils.h>
#include <chord.h>
#include <id_utils.h>
#include "rpclib.h"

#include <vector>

class SyncChordClient {
        chord_node node;
	std::vector<chord_node> slist;
	bool getsuclistok;

        public:
                SyncChordClient(char * hostname,unsigned int port) {
                        warn << "SyncChordClient::SyncChordClient()\n";
                        if (inet_addr (hostname) == INADDR_NONE) {
                                // yep, this still blocks.
                                struct hostent *h = gethostbyname (hostname);
                                if (!h)
                                        fatal << "Invalid address or hostname: " << hostname << "\n";
                                struct in_addr *ptr = (struct in_addr *) h->h_addr;
                                node.r.hostname = inet_ntoa (*ptr);
                        } else {
                                node.r.hostname = hostname;
                        }
                        node.r.port=port;
                        node.x = make_chordID (node.r.hostname, node.r.port);
                        node.vnode_num = 0;
                }

                std::vector<chord_node> getSuccList() {
			slist.clear();
			getsuclistok=false;
                        warn << "SyncChordClient::getSuccList()\n";
                        chord_nodelistres *res = New chord_nodelistres (CHORD_OK);
                        ptr<chordID> v = New refcounted<chordID> (node.x);
                        doRPC (node, chord_program_1,
                                CHORDPROC_GETSUCCLIST, v, res,
                                wrap (this, &SyncChordClient::getSuccList_cb, res));
			warn << "SyncChordClient::getSuccList() - acheck\n";
			acheck();
			warn << "SyncChordClient::getSuccList() - done\n";
			if (!getsuclistok) {
				warn << "Cos zlego sie stalo...\n";
				// FIXME: tu rzucić wyjątek
			}
			return slist;
                }

                void getSuccList_cb(chord_nodelistres *res, clnt_stat err) {
                        warn << "SyncChordClient::getSuccList_cb()\n";
			for (size_t i = 0; i < res->resok->nlist.size (); i++) {
				chord_node z = make_chord_node (res->resok->nlist[i]);
				slist.push_back(z);
				assert (z.vnode_num >= 0);
			}
			getsuclistok=(err==RPC_SUCCESS);
                }

};


int main() {
        SyncChordClient c("lotlap.riviera.pw.edu.pl",10000);
        std::vector<chord_node> l=c.getSuccList();

	for (std::vector<chord_node>::const_iterator i=l.begin();i!=l.end();++i) {
		// ID, host, port, nr vwezla
		warn << i->x << "\t" << i->r.hostname << "\t" << i->r.port << "\t" << i->vnode_num << "\n";
	}

	
	return 0;
}


